from typing import Optional
import redis.asyncio as redis

redis_server = None


async def set_tool(
    key: str,
    value: str,
    ex: Optional[int] = None,
) -> str:
    """
    Set the value of a key in Redis.
    """
    if redis_server is None:
        return "Redis server not initialized"

    try:
        client = await redis_server.get_connection()  # type: ignore

        result = await client.set(key, value, ex=ex)

        if result:
            message = f"successfully"
            if ex:
                message += f", expire time {ex} seconds"
            return message
        else:
            return f"set '{key}' failure"

    except redis.RedisError as e:
        return f"Redis Error: {str(e)}"
    except Exception as e:
        return f"set '{key}' error: {str(e)}"
